import pickle

import base64
from django_redis import get_redis_connection

def merge_cookie_to_redis(request,user,response):

    # 1.获取cookie信息
    cookie_str = request.COOKIES.get('cart')
    if cookie_str is not None:
        #说明有cart数据,我们对cart数据进行解密
        cookie_cart = pickle.loads(base64.b64decode(cookie_str))

        redis_conn = get_redis_connection('cart')

        sku_id_counts = redis_conn.hgetall('cart_%s'%user.id)

        selected_ids = []
        redis_conn_ids = {}

        for sku_id,count in sku_id_counts.items():
            redis_conn_ids[int(sku_id)] = int(count)

        for sku_id,count_selected in cookie_cart.items():

            if sku_id in redis_conn_ids:
                redis_conn_ids[sku_id]=count_selected['count']
            else:
                redis_conn_ids[sku_id]=count_selected['count']

            if count_selected['selected']:
                selected_ids.append(sku_id)

        redis_conn.hmset('cart_%s'%user.id,redis_conn_ids)

        redis_conn.sadd('cart_selected_%s'%user.id,*selected_ids)

        response.delete_cookie('cart')

        return response
    else:
        return response